package com.bsoft.gol.editor.fileUpload;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.List;

public class RowParser {

	public static void parseRow(AbstractInExcel instance, Row row, List<Field> fields, List<String> emptyIdentities){
		try{
			boolean allEmpty = true;
			for(Field field : fields){
				field.setAccessible(true);
				ColumnRelation annotation = field.getAnnotation(ColumnRelation.class);
				Object value = getCellValue(row.getCell(annotation.colIndex()));
				if(allEmpty && value != null && !annotation.defaultValue().equals(value.toString())){//都为空则返回null对象
					allEmpty = false;
				}
				try{
					field.set(instance, value);
				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
			if(allEmpty){
				instance.setEmptyRow(allEmpty);
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	private static Object getCellValue(Cell cell){
    	if(cell == null){
    		return null;
    	}
    	int cellType = cell.getCellType();
    	Object value = null;
    	if(cellType == Cell.CELL_TYPE_NUMERIC){
    		if(HSSFDateUtil.isCellDateFormatted(cell)){
        		value = cell.getDateCellValue();
        	}else{ 
        		DecimalFormat df = new DecimalFormat("#.######");
        		value =	df.format(cell.getNumericCellValue());
        	}
    	}else if(cellType == Cell.CELL_TYPE_STRING){
    		value = cell.getStringCellValue();
    	}
    	return value;
    }
}
